from django.shortcuts import render,loader,redirect
from django import http
from django.urls import reverse

from .models import Goods
# Create your views here.
from django.views import View

class GoodView(View):
    def get(self,request):
        goods=Goods.objects.all()
        context={
            'goods':goods,
        }
        return render(request,'goods.html',context)

    def post(self,request):
        good=Goods()
        try:
            good.name = request.POST.get('good_name')
            good.price = request.POST.get('good_price')
            good.stock = request.POST.get('good_stock')
            good.sales = request.POST.get('good_sales')
            good.save()
            return redirect(reverse('goods:info'))
        except Exception as e:
            return http.HttpResponseForbidden('数据错误')




class UpdateDestroyGood(View):
    def get(self, request, gid=None):
        try:
            good=Goods.objects.get(id=gid)
            good.delete()
        except Exception as e:
            return http.HttpResponseForbidden('删除失败')
        return redirect(reverse('goods:info'))

    def post(self,request):
        goods=Goods.objects.get()
        count=goods.count()
        try:
            num=request.POST.get('good_num')
            for i  in range(1,count+1):
                if i ==int(num):
                    good=goods[i-1]
                    good.name=request.POST.get('good_name')
                    good.price = request.POST.get('good_price')
                    good.stock = request.POST.get('good_stock')
                    good.sales = request.POST.get('good_sales')
                    good.save()
                    break
        except Exception as e:
            return http.HttpResponseForbidden("编辑失败")
        return  redirect(reverse())